// pages/comment/comment.js
const app = getApp()
var service = require('../../util/service');
var util = require('../../util/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selcomment:1,
    exhibitions:[],
    comments:[],
    comment:"",
    commentpla:"写评论",
    submitstr:"发送",
    relId:"",
    relType:"",
    hhid:"",
    hhname:"",
    lodding: false,
    loddtext: "加载中……",
    additions:"",
    pageSize: 10,
    page: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var type = options.type||0;
    var id = options.id;
    var rtype = options.type;
    
    this.setData({
      relId: id,
      relType: rtype
    })
    this.setData({
      'selcomment': 1,
      'page': 1,
      comments: [],
      additions: ""
    });
    this.getComments();
  },
  bindFormSubmit(e) {
    if (!e.detail.value.comment) {
      this.setData({
        commentpla: "写评论",
        submitstr: "发送",
        hhid:"",
        hhname:""
      })
      return;
    }
    var user = app.userInfo;
    var commentObj = {
      userId: user.buyId,
      commentText: e.detail.value.comment,
      thumbsNumber:0,
      relType:this.data.relType,
      relId:this.data.relId
    }
    if(this.data.hhid){
      commentObj.parentId = this.data.hhid;
      commentObj.relType = "Comment";
      commentObj.relId = this.data.hhid;
    }
    let hhid = this.data.hhid;
    service.AJAX(`smc/topic/BasicComments/addBasicComments.do`, commentObj, res => { 
      this.setData({
        commentpla: "写评论",
        submitstr: "发送",
        hhid: "",
        hhname: "",
        comment: ""
      })
      this.getComments(true, commentObj.parentId);
      if (hhid) {
        let msgcomment = this.gitCommentByid(hhid);
        if (!msgcomment) return;
        //拼接评论消息并存储
        var msg = {};
        msg.sourceUserId = user.buyId;
        msg.descUserId = msgcomment.userId;  
        var msgText = {
          date: util.getTime(),
          type: 0,//0评论 1点赞
          reply: commentObj.commentText,
          headurl: user.pic,
          name: user.buyName,
          comment: {
            relId: commentObj.relId,
            relType:"Comment",
            headurl: msgcomment.userid_pic,
            name: msgcomment.userid_buyName,
            comment: msgcomment.commentText,
            date: msgcomment.createdAtStr
          }
        }
        msg.relId = commentObj.relId;
        msg.relType = "Comment";
        msg.msgText = JSON.stringify(msgText);
        service.AJAX(`smc/topic/MessageObject/addMessageObject.do`, msg, res => {}, err => { }, "POST");
      }
      
    }, err => { }, "POST");
  },
  gitCommentByid:function(id){
    var comments = this.data.comments;
    for (var i = 0; i < comments.length;i++){
      if (comments[i].commentId == id){
        return comments[i];
      }
    }
  },
  lower: function () {
    this.setData({
      'page': this.data.page + 1
    })
    this.getComments();
  },
  getComments: function (sx, parentId){
    var that = this;
    that.setData({
      lodding: true,
      loddtext: "加载中……"
    })
    //page=1,pagesize=20
    //$childrenCount-additions=1 获取回复下面的数量
    service.AJAX("smc/topic/BasicComments/queryBasicComments.json?$$uid=" + app.userInfo.buyId + "&$relId=" + this.data.relId + "&$relType=" + this.data.relType + "&$childrenCount-additions=1&$parentId=0&$sortType-additions=" + this.data.additions,
      { page: this.data.page, pageSize: this.data.pageSize},
      res => {
        console.log(res);
        var results = res.rows;
        if (!results || results.length <= 0){
          that.setData({
            page: this.data.page-1,
            lodding: true,
            loddtext: "没有更多数据了"
          })
          return;
        } 
        var lodd = results.length < 10;
        for (var i = 0; i < results.length; i++) {
          var data = results[i];
          if (data.createdAt) {
            data.createdAtStr = util.getTime(data.createdAt);
          }
          data.zanicon = data.is_praise == 1 ? "../../images/photo/zans.png" :"../../images/photo/zan.png";
          if (sx) {
            var comment = that.data.comments[(this.data.page - 1) * this.data.pageSize + i];
            if (comment){
              data.zkcomment = comment.zkcomment;
              comment = data;
            }else{
              that.data.comments.push(data);
            }
          }else{
            data.zkcomment = false;
          }
        }
        if (sx){
          if (parentId){
            for (var i = 0; i < that.data.comments.length; i++){
              if (that.data.comments[i].commentId == parentId){
                that.data.comments[i].childrenCount = that.data.comments[i].childrenCount+1;
              }
            }
          }
          that.setData({
            comments: that.data.comments,
            lodding: lodd,
            loddtext: lodd ? "没有更多数据了" : "加载中……"
          })
        }else{
          var data = that.data.comments.concat(results);
          that.setData({
            comments: data,
            lodding: lodd,
            loddtext: lodd ? "没有更多数据了" : "加载中……"
          })
        }
        
      }, err => { }, 'POST')
  },
  hhomment:function(e){
    var id = e.target.dataset.id;
    var name = e.target.dataset.name;
    this.setData({
      commentpla: "回复:" + name,
      submitstr: "取消回复",
      hhid: id,
      hhname: name
    })
  },
  bindKeyInput(e){
    var val = e.detail.value;
    if(val){
      if(this.data.hhid){
        this.setData({
          submitstr: "回复"
        })
      }else{
        this.setData({
          submitstr: "发送"
        })
      }
    }else{
      if (this.data.hhid) {
        this.setData({
          submitstr: "取消回复",
          commentpla: "回复:"+this.data.hhname
        })
      } else {
        this.setData({
          commentpla: "写评论",
          submitstr: "发送"
        })
      }
    }
  },
  zans: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var replyindex = e.currentTarget.dataset.replyindex;
    var comments = this.data.comments;
    var comment = comments[index];
    var state = !(comment.is_praise==1);
    if (replyindex || replyindex == 0){
      comment = comment.replys[replyindex];
      state = !(comment.is_praise == 1);
    }
    var user = app.userInfo;
    //获取点赞集合判断用户是否对改机构进行过点赞
    service.AJAX2(`smc/dim/RecordPraiseRel/dealRecordPraiseRel.do`, { relId: id, userId: app.userInfo.buyId, relType: 'Comment' }, res => {
      if (res > 0) {
        var title = "", msgrpe="";
        if (state) {
          comment.zanicon = "../../images/photo/zans.png";
          title = "点赞成功";
          comment.thumbsNumber = comment.thumbsNumber + 1;
          comment.is_praise = 1
          msgrpe = "点赞了";
        } else {
          comment.zanicon = "../../images/photo/zan.png";
          title = "取消点赞成功";
          comment.thumbsNumber = comment.thumbsNumber - 1;
          comment.is_praise = 0
          msgrpe = "取消了点赞";
        }
        
        wx.showToast({
          title: title,
          icon: 'succes',
          duration: 1000,
          mask: true
        })
        this.setData({
          comments: comments
        });
        //拼接评论消息并存储
        var msg = {};
        msg.sourceUserId = user.buyId;
        msg.descUserId = comment.userId;
        var msgText = {
          date: util.getTime(),
          type: 1,//0评论 1点赞
          reply: user.buyName + msgrpe,
          headurl: user.pic,
          name: user.buyName,
          comment: {
            relId: comment.commentId,
            relType: "Comment",
            headurl: comment.userid_pic,
            name: comment.userid_buyName,
            comment: comment.commentText,
            date: comment.createdAtStr
          }
        }
        msg.relId = comment.commentId;
        msg.relType = "Comment";
        msg.msgText = JSON.stringify(msgText);
        service.AJAX(`smc/topic/MessageObject/addMessageObject.do`, msg, res => { }, err => { }, "POST");
      } else {
        wx.showToast({
          title: "系统异常请稍后再试",
          icon: 'error',
          duration: 1000,
          mask: true
        })
      }
    }, err => { }, 'GET', true)
  },
  zkcomment:function(e){
    var that = this;
    let index = e.currentTarget.dataset.index;
    let comments = this.data.comments;
    let comment = comments[index];
    let commentId = comment.commentId;
    service.AJAX(`smc/topic/BasicComments/queryBasicComments.json?$$uid=${app.userInfo.buyId}&$relId=${commentId}&$relType=Comment&$parentId=${commentId}`,{ page: 1, pageSize: 100 },res => {
        var results = res.rows;
        for (var i = 0; i < results.length; i++) {
          var data = results[i];
          if (data.createdAt) {
            data.createdAtStr = util.getDate(data.createdAt);
          }
          data.zanicon = data.is_praise == 1 ? "../../images/photo/zans.png" : "../../images/photo/zan.png";
        }
        comment.replys = results;
        comment.zkcomment = !comment.zkcomment;
        that.setData({
          comments: comments
        })
      }, err => { }, 'POST')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selindex: function () {
    this.setData({
      'selcomment': 1,
      'page': 1,
      comments: [],
      additions: ""
    });
    this.getComments();
  },
  selindex2: function () {
    this.setData({
      'selcomment': 2,
      'page': 1,
      comments: [],
      additions: "LOOK"
    })
    this.getComments();
  },
  selindex3: function () {
    this.setData({
      'selcomment': 3,
      'page': 1,
      comments: [],
      additions: "COUNT"
    })
    this.getComments();
  }
})